package com.tsin.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsin.usercenter.common.BaseResponse;
import com.tsin.usercenter.common.ErrorCode;
import com.tsin.usercenter.common.ResultUtils;
import com.tsin.usercenter.exception.BusinessException;
import com.tsin.usercenter.model.User;
import com.tsin.usercenter.model.request.UserLoginRequest;
import com.tsin.usercenter.model.request.UserRegisterRequest;
import com.tsin.usercenter.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import static com.tsin.usercenter.common.ErrorCode.NULL_ERROR;
import static com.tsin.usercenter.constant.UserConstant.ADMIN_ROLE;
import static com.tsin.usercenter.constant.UserConstant.USER_LOGIN_KEY;

/**
 * @author 佳宏
 * 用户接口 API
 */
@Slf4j
@RestController
@CrossOrigin(origins = {"http://101.200.127.11"}, allowCredentials = "true")
@RequestMapping("/user")
@Tag(name = "用户控制层")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 注册API
     *
     * @param userRegisterRequest 注册请求
     * @return userId
     */
    @PostMapping("register")
    @Operation(summary = "注册", description = "注册2")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            return null;
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long userId = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(userId);
    }

    /**
     * 登录API
     *
     * @param userLoginRequest   登录请求
     * @param httpServletRequest 状态请求
     * @return saveUser
     */
    @PostMapping("/login")
    public BaseResponse<Long> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest httpServletRequest) {
        if (userLoginRequest == null) {
            return ResultUtils.error(NULL_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        Long userId = userService.userDoLogin(userAccount, userPassword, httpServletRequest);
        return ResultUtils.success(userId);
    }
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest httpServletRequest){
        //校验参数是否为空
        if(user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(httpServletRequest);
        //触发更新
        Integer result = userService.updateUser(user,loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 查询API
     *
     * @param nickName           昵称
     * @param httpServletRequest 状态请求
     * @return List<User>
     */
    @GetMapping("/search")
    public List<User> searchUser(String nickName, HttpServletRequest httpServletRequest) {
        //仅管理员可查
        if(!userService.isAdmin(httpServletRequest)){
            return null;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(nickName)) {
            queryWrapper.like("nick_name", nickName);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list).getData();
    }

    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize,long pageNum) {
        //如果缓存中有，直接读缓存
        String redisKey = String.format("youni:user:recommend:public");
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        Page<User> userList =(Page<User>)stringObjectValueOperations.get(redisKey);
        if(userList!=null){
            return ResultUtils.success(userList);
        }
        //没有就走数据库,并写入缓存
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userList = userService.page(new Page<>(pageNum,pageSize),queryWrapper);
        try {
            stringObjectValueOperations.set(redisKey,userList,30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis缓存数据发生错误", e);
        }
        return ResultUtils.success(userList);
    }



    @GetMapping("/search/tags")
    public BaseResponse<Page<User>>searchUsserByTags(@RequestParam(required = false)List<String> tagList,int pageSize,int pageNum) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for (String tagName : tagList) {
            queryWrapper = queryWrapper.like("tags", tagName);
        }
        Page<User> userTagsList = userService.page(new Page<>(pageNum,pageSize),queryWrapper);
        return ResultUtils.success(userTagsList);
    }

    /**
     * 删除API
     *
     * @param id                 id
     * @param httpServletRequest 状态请求
     * @return *
     */
    @GetMapping("/delete")
    public BaseResponse<Boolean> deleteUser(long id, HttpServletRequest httpServletRequest) {
        Long userId = userService.getLoginUser(httpServletRequest).getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (id!=userId){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.removeById(userId);
        return ResultUtils.success(result);
    }

    /**
     * 账户登录状态请求API
     * @param httpServletRequest
     * @return safetyUser
     */
    @GetMapping("/current")
    public  BaseResponse<User> getCurrentUser(HttpServletRequest httpServletRequest) {
        Object userObject = httpServletRequest.getSession().getAttribute(USER_LOGIN_KEY);
        User currentUser = (User) userObject;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        // todo 校验用户合法性
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);

    }

    /**
     * 用户注销
     *AWAWD
      * @param httpServletRequest
     * @return
     */
    @PostMapping("logout")
    public  BaseResponse<Boolean> userLoginOut( HttpServletRequest httpServletRequest) {
        if (httpServletRequest == null) {
            return null;
        }
        userService.userLoginOut(httpServletRequest);
        return ResultUtils.success(true);
    }



    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //如果缓存中有，直接读缓存
        Long id = userService.getLoginUser(request).getId();
        String redisKey = String.format("youni:user:match:%s",id);
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        List<User> userList =(List<User>)stringObjectValueOperations.get(redisKey);
        if(userList!=null){
            return ResultUtils.success(userList);
        }
        //没有就走数据库,并写入缓存
        User user = userService.getLoginUser(request);
        userList = userService.matchUsers(num, user);
        try {
            stringObjectValueOperations.set(redisKey,userList,1200000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis缓存数据发生错误", e);
        }
        return ResultUtils.success(userList);
    }
}